package com.bot.devbot.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bot.devbot.pojo.req.GitlabCommitInfoReq;
import com.bot.devbot.pojo.res.GitlabCommitInfoRes;
import com.bot.devbot.service.feishu.FeiShuService;
import com.bot.devbot.service.gitlab.GitLabService;
import com.bot.devbot.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取gitlab仓库信息控制器
 *
 * @author xialiguo
 * @version 1.0
 * @date 2025/2/14 15:46
 * @since 1.0
 */
@Slf4j
@RestController
@RequestMapping("/gitlab")
public class GitLabInfoController {

    @Autowired
    private GitLabService gitLabService;

    @PostMapping("/getCommitInfo")
    public Object getCommitInfo(@RequestBody GitlabCommitInfoReq req) {

        String projectId = req.getProjectId();
        String targetBranch = req.getBranch();
        List<String> commitList = new ArrayList<>();

        JSONArray branches = gitLabService.getBranchesV2(projectId);
        // 遍历所有分支
        for (Object branchObj : branches) {
            JSONObject branch = (JSONObject) branchObj;
            String branchName = branch.getStr("name");
            if (StrUtil.isNotBlank(targetBranch) && !branchName.equals(req.getBranch())) {
                continue;
            }

            JSONArray commits = gitLabService.getAllCommits(projectId, branchName);
            log.info("projectId:{},branchName:{}", projectId, branchName);
            String author = req.getAuthor();
            // 倒序遍历
            for (int i = commits.size() - 1; i >= 0; i--) {
                JSONObject commit = commits.getJSONObject(i);
                GitlabCommitInfoRes commitInfo = new GitlabCommitInfoRes();
                commitInfo.setAuthor(commit.getStr("author_name"));
                commitInfo.setDate(DateUtil.timeFromGitlabToLocal(commit.getStr("created_at")));
                commitInfo.setTitle(commit.getStr("title"));
                String msg = "[" + commitInfo.getDate() + "]    " + commitInfo.getTitle();
                if (commitList.contains(msg)) {
                    continue;
                }
                if (StrUtil.isNotBlank(author)) {
                    if (commitInfo.getAuthor().equals(author)) {
                        commitList.add(msg);
                    }
                } else {
                    commitList.add(msg);
                }
            }

        }
        return commitList;
    }
}
